const db = uniCloud.database();
const { groupApplySendMessage } = require('../push/index.js');
const { defaultChpaters } = require('../../config/index.js');
module.exports = async function(options = {}) {
	const { characterId, groupCode } = options;
	const token = this.getUniIdToken();
	if (!characterId || !token) {
		throw new Error('非法访问');
	}
	const [groupRes, applyRes] = await Promise.all([
		db.collection('a-dz-group-list').where({ groupCode }).get({ getOne: true }),
		db.collection('a-dz-group-apply-list').where({ characterId, groupCode }).get({ getOne: true })
	])
	if (!groupRes.data.length) {
		return {
			code: -3,
			msg: '该群组不存在或关闭邀请'
		}
	} else if (groupRes.data[0].status != 'ACTIVATED') {
		return {
			code: -3,
			msg: '该群组还未激活'
		}
	}
	if (applyRes.data.length) {
		await Promise.all([
			db.collection('a-dz-group-apply-list').doc(applyRes.data[0]._id).update({
				...options,
				applyStatus: 'APPLYING',
				updateTime: Date.now()
			}),
			groupApplySendMessage({
				groupItem: groupRes.data[0]
			})
		])
	} else {
		await Promise.all([
			db.collection('a-dz-group-apply-list').add({
				...options,
				applyStatus: 'APPLYING',
				createTime: Date.now()
			}),
			groupApplySendMessage({
				groupItem: groupRes.data[0]
			})
		])
	}
	return {
		code: 0,
		msg: '申请成功'
	}
}